<template>
  <span>
    <svg
      v-if="!success"
      class="icon icon-copy"
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      @click="handleClick"
    >
      <path
        d="M11.6627 4.82906V13.8346C11.6627 14.1108 11.4389 14.3346 11.1627 14.3346H2.16699C1.89085 14.3346 1.66699 14.1108 1.66699 13.8346V4.82906C1.66699 4.55292 1.89085 4.32906 2.16699 4.32906H11.1627C11.4389 4.32906 11.6627 4.55292 11.6627 4.82906ZM10.6631 5.32962H2.66657V13.3341H10.6631V5.32962ZM14.3337 2.16797V11.5071C14.3337 11.7832 14.1098 12.0071 13.8337 12.0071H12.3314C12.332 11.455 12.7793 11.0069 13.3314 11.0058L13.3341 11.0058V2.66786H5.00431V2.79239C5.00431 3.34444 4.55679 3.79197 4.00474 3.79197V2.16797C4.00474 1.89183 4.2286 1.66797 4.50474 1.66797H13.8337C14.1098 1.66797 14.3337 1.89183 14.3337 2.16797Z"
        fill="currentColor"
      />
    </svg>
    <svg
      v-else
      class="icon icon-success"
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        fill-rule="evenodd"
        clip-rule="evenodd"
        d="M12.4853 0.366175C12.8758 -0.0242967 13.509 -0.0242159 13.8995 0.366286L4.70711 9.55867C4.57865 9.68596 4.37062 9.68644 4.24264 9.55867L0 5.31603C0.390519 4.92552 1.02368 4.92553 1.41418 5.31607L4.474 8.37618L12.4853 0.366175Z"
        fill="currentColor"
      />
    </svg>
  </span>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue";
const props = defineProps<{ text: string }>();
const success = ref(false);
let timer = 0;
const handleClick = () => {
  try {
    const { text } = props;
    if (navigator.clipboard) {
      // clipboard api 复制
      navigator.clipboard.writeText(text);
    } else {
      var textarea = document.createElement("textarea");
      // 隐藏此输入框
      textarea.style.position = "fixed";
      textarea.style.clip = "rect(0 0 0 0)";
      textarea.style.top = "10px";
      // 赋值
      textarea.value = text;
      document.body.appendChild(textarea);
      // 选中
      textarea.select();
      // 复制
      document.execCommand("copy", true);
      // 移除输入框
      document.body.removeChild(textarea);
    }
    success.value = true;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      success.value = false;
      timer = 0;
    }, 3000);
  } catch (e) {
    console.error(e);
  }
};
onBeforeUnmount(() => {
  if (timer) {
    clearTimeout(timer);
  }
});
</script>
<style lang="css">
.icon {
  width: 16px;
  height: 16px;
  vertical-align: text-bottom;
  color: #00b3be;
}
.icon-copy {
  cursor: pointer;
}
@keyframes success {
  0% {
    transform: scale(1.4);
    opacity: 0;
  }
  50% {
    transform: scale(1.5);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
.icon-success {
  animation: success 0.5s ease;
}
</style>
